<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../css/bootstrap.css" type="text/css" rel="stylesheet"/>
    <link href="../css/Buttons.css" type="text/css" rel="stylesheet"/>
    <style>
        #main {
            margin: 0 auto;
            width: 800px;
        }
        .nav-First {
            list-style: none;
            display: flex;
        }
        .nav-First li {
            margin: 5px;
            background: gray;
            flex: 1;
            text-align: center;
            font-size: 20px;
            cursor: pointer;
            border-radius: 5px;
            color: white;
        }
        #content-First {
            width: 100%;
        }
        .clearfix::after {
            clear: both;
            visibility: hidden;
            height: 0;
            width: 100%;
        }
        .content-Second {
            margin-left: 30px;
            width: 100%;
        }
        .title-Third {
            vertical-align: middle;
            margin-right: 10px;
        }
        .title-Type {
            vertical-align: middle;
            margin-right: 10px;
        }
        .content-Third {
            margin-left: 250px;
            width: 500px;
        }
        .nav-Second {
            float: left;
            width: 200px;
        }
        .nav-Second li {
            font-size: 20px;
            text-align: center;
            border: 1px dotted black;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .list-item {
            cursor: pointer;
            border-radius: 5px;
            margin: 3px;
            overflow: hidden;
            border: 1px solid #1B9AF7;
        }
        .list-item-title {
            height: 30px;
            line-height: 30px;
            font-size: 15px;
            text-align: center;
            background: #1B9AF7;
            color: white;
            float: left;
            width: 100px;
        }
        .list-item-content {
            text-indent: 10px;
            height: 30px;
            line-height: 30px;
            margin-left: 100px;
            font-size: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 350px;
        }
        .list-item-input {
            width: 350px;
            display: block;
            text-indent: 10px;
            height: 30px;
            line-height: 30px;
            margin-left: 100px;
            font-size: 15px;
            border: 0;
            outline: 0;
        }
        .list-item-head {
            padding: 5px;
            background: #1B9AF7;
            float: left;
            color: white;
        }
        .list-item-body {
            background: white;
            float: left;
            padding: 5px;
        }
        .search-Input {
            height: 28px;
        }
        .type-Item {
            text-align: center;
            border-radius: 10px;
            cursor: pointer;
            width: content-box;
            border: 1px solid #1B9AF7;
            padding: 5px;
            margin: 5px;
        }
    </style>
</head>
<div id="main">
    <div style="width: 100%; text-align: right;"><button class="button button-primary button-small" style="margin: 10px;" onclick="manageLogout()">Log Out</button><br/></div>
    <ul class="nav-First">
        <li onclick="firstShowAndHideOther(0)">User</li>
        <li onclick="firstShowAndHideOther(1)">Type</li>
        <li onclick="firstShowAndHideOther(2)">Product</li>
        <li onclick="firstShowAndHideOther(3)">Order</li>
    </ul>
    <div id="content-First">
        <div class="clearfix" id="userBox" style="display: none;">
            <div class="content-Second">
                <ul class="nav-Second">
                    <li onclick="secondShowAndHideOther(0, 0); userController(0);">User List</li>
                </ul>
                <div class="content-Third">
                    <h1>User</h1>
                    <hr />
                    <div id="userListBox" style="display: none;">
                        <div id="userListBox-content"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="clearfix" id="typeBox" style="display: none;">
            <div class="content-Second">
                <ul class="nav-Second">
                    <li onclick="secondShowAndHideOther(1, 0); typeController(0);">Type List</li>
                </ul>
                <div class="content-Third">
                    <h1>Type</h1>
                    <hr />
                    <div id="typeListBox" style="display: none;">
                        <div id="typeListBox-content"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="clearfix" id="productBox" style="display: none;">
            <div class="content-Second">
                <ul class="nav-Second">
                    <li onclick="secondShowAndHideOther(2, 0); productController(0);">Product List</li>
                    <li onclick="secondShowAndHideOther(2, 1); productController(1);">Add Product</li>
                </ul>
                <div class="content-Third">
                    <h1>Product</h1>
                    <hr />
                    <div id="productListBox" style="display: none;">
                        <div id="productListBox-content"></div>
                    </div>
                    <div id="productAddBox" style="display: none;">
                        <h3>Add Product</h3>
                        <div id="productAddBox-content"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="clearfix" id="orderBox" style="display: none;">
            <div class="content-Second">
                <ul class="nav-Second">
                    <li onclick="secondShowAndHideOther(3, 0); orderController(0);">Order List</li>
                </ul>
                <div class="content-Third">
                    <h1>Order</h1>
                    <hr />
                    <div id="orderListBox" style="display: none;">
                        <div id="orderListBox-content"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<body>
<script src="../js/jquery-3.2.1.min.js"></script>
<script>
    const manageLogoutUrl = `/manage/user/logout`;

    const userGetListUrl = `/manage/user/list`;
    const userSetRoleUrl = `/manage/user/set_user_role`;

    const categoryGetChildUrl = `/manage/category/get_category`;
    const categoryAddUrl = `/manage/category/add_category`;
    const categorySetNameUrl = `/manage/category/set_category_name`;
    const categoryGeyByIdUrl = `/manage/category/get_by_id`;

    const productGetCountUrl = `/manage/product/get_by_namelike`;
    const productGetListUrl = `/manage/product/list`;
    const productSearchListUrl = `/manage/product/search`;
    const productUploadPictureUrl = `/manage/product/upload`;
    const productDetailUrl = `/manage/product/detail`;
    const productSetSaleStatusUrl = `/manage/product/set_sale_status`;
    const productSaveUrl = `/manage/product/save`;
    const productUploadBothPictureAndRichTextUrl = `/manage/product/richtext_img_upload`;

    const orderGetListUrl = `/manage/order/list`;
    const orderSearchListUrl = `/manage/order/search`;
    const orderDetailUrl = `/manage/order/detail`;
    const orderSendGoodsUrl = `/manage/order/sendgoods`;

    const getUserInfoUrl = `/user/get_user_info`;
    let elemArray = [
        {
            elem: $("#userBox"),
            children: [{
                elem: $("#userListBox"),
                get: false}],
            get: false
        },
        { elem: $("#typeBox"), children: [{ elem: $("#typeListBox"), get: false}], get: false },
        { elem: $("#productBox"), children: [{elem: $("#productListBox"), get: false}, {elem: $("#productAddBox"), get: false}], get: false},
        { elem: $("#orderBox"), children: [{elem: $("#orderListBox"), get: false}], get: false }
    ];
    
    function manageLogout() {
        $.get(manageLogoutUrl, function (result) {
            if (result.success) {
                window.location.href = `/admin/login`;
            }
            else {
                alert(result.msg);
            }
        });
    }
    
    $(document).ready(function () {
        $.get(getUserInfoUrl, function (result) {
            console.log(result);
            if (result.success) {

            }
            else {
                window.location.href = "/admin/login";
            }
        });
        user = new User();
        type = new Type();
        product = new Product();
        order = new Order();
    });
    function firstShowAndHideOther(index) {
        for (let i = 0; i < elemArray.length; i++) {
            if (i === index) {
                elemArray[i].elem.show();
            }
            else {
                elemArray[i].elem.hide();
            }
        }
    }
    function secondShowAndHideOther(index1, index2) {
        let temp = elemArray[index1].children;
        for (let i = 0; i < temp.length; i++) {
            if (i === index2) {
                temp[i].elem.show();
            }
            else {
                temp[i].elem.hide();
            }
        }
    }
    function thirdShowAndHideOther(index1, index2, index3) {
        let temp = elemArray[index1].children[index2].children;
        if (temp != null) {
            for (let i = 0; i < temp.length; i++) {
                if (i === index3) {
                    temp[i].elem.show();
                }
                else {
                    temp[i].elem.hide();
                }
            }
        }
    }
    let orderState = { getOrder: 0 };
    function orderController(stateNumber) {
        switch (stateNumber) {
            case orderState.getOrder:
                order.getOrder();
                break;
        }
    }
    let order;
    class Order {
        constructor() {
            this.orderListBoxContent = $("#orderListBox-content");
            this.searchText = "";
            this.pageSize = 10;
            this.pageNum = 1;
            this.orderListJSON = [];
            this.utils = new Utils();
            this.pageTotal = 0;
        }

        getOrder() {
            let tempJSON;
            let ajaxUrl;
            if (this.searchText == null || this.searchText.length === 0) {
                ajaxUrl = orderGetListUrl;
                tempJSON = { pageNum: this.pageNum, pageSize: this.pageSize };
                $.get(ajaxUrl, tempJSON, function (result) {
                    if (result.success) {
                        if (result.data == null) {
                            this.orderListJSON = [];
                        }
                        else {
                            if (result.data.list == null) {
                                this.orderListJSON = [];
                                this.pageTotal = 0;
                            }
                            else {
                                this.orderListJSON = result.data.list;
                                this.pageTotal = Math.ceil(result.data.total / this.pageSize);
                            }
                        }
                    }
                    else {
                        this.orderListJSON = [];
                        this.pageTotal = 0;
                    }
                    this.showOrder();
                }.bind(this));
            }
            else {
                ajaxUrl = orderSearchListUrl;
                tempJSON = { orderno: this.searchText };
                $.post(ajaxUrl, tempJSON, function (result) {
                    if (result.success) {
                        if (result.data == null) {
                            this.orderListJSON = [];
                        }
                        else {
                            if (result.data.list == null) {
                                this.orderListJSON = [];
                            }
                            else {
                                this.orderListJSON = result.data.list;
                            }
                        }
                    }
                    else {
                        this.orderListJSON = [];
                    }
                    this.showOrder();
                }.bind(this));
            }
        }

        showOrder() {
            let orderListJSON = this.orderListJSON;
            let content = this.orderListBoxContent;
            content.html("<h3><span class='title-Third'>Order List</span></h3>");
            content.append(`<div>Order Number : <input style="vertical-align: middle;" class="search-Input" value="${this.searchText}" type="text" id="orderSearchInput" placeholder="input order id here."/>
                <button style="vertical-align: middle;" class="button button-primary button-small" id="orderSearchBtn">Search</button></div><br/>
            `);
            $("#orderSearchBtn").click(function () {
                this.searchText = $("#orderSearchInput").val();
                this.pageNum = 1;
                this.getOrder();
            }.bind(this));
            let elemStr = "";
            if (orderListJSON.length === 0) {
                elemStr += `<div>Not found.</div>`;
            }
            for (let item of orderListJSON) {
                let statusText = this.getStatusText(item.status);
                content.append(`<div class="list-item" id="orderDetail${item.orderNo}"><div class="list-item-head">Order Number</div>
                    <div class="list-item-body">${item.orderNo}</div>
                    <div class="list-item-head">Status</div><div class="list-item-body">${statusText}</div></div>
                `);
                $(`#orderDetail${item.orderNo}`).click(function () {
                    this.showDetail(item.orderNo);
                }.bind(this));
            }
            content.append(elemStr);
            content.append(`<br/><button class="button button-primary button-small" id="orderPreviousPageBtn">Previous Page</button>
                <button class="button button-primary button-small" id="orderNextPageBtn">Next Page</button>
            `);
            $(`#orderPreviousPageBtn`).click(function () {
                this.previousPage();
            }.bind(this));
            $(`#orderNextPageBtn`).click(function () {
                this.nextPage();
            }.bind(this));
        }

        showDetail(orderNo) {
            let content = this.orderListBoxContent;
            content.html("");
            content.append(`<h3><span class='title-Third'>Order Detail</span><button style="vertical-align: middle;"
                class="button button-primary button-small"  id="backToOrderList">Back</button></h3>`);
            $("#backToOrderList").click(function () {
                this.showOrder();
            }.bind(this));
            let orderJSON = this.utils.getItem(this.orderListJSON, "orderNo", orderNo);
            content.append(`
                <div class="list-item"><div class="list-item-title">Order Number</div><div class="list-item-content">${orderJSON.orderNo}</div></div>
                <div class="list-item"><div class="list-item-title">Payment</div><div class="list-item-content">${orderJSON.payment}</div></div>
                <div class="list-item"><div class="list-item-title">Status</div><div class="list-item-content">${this.getStatusText(orderJSON.status)}</div></div>
            `);
            if (orderJSON.status === 20) {
                content.append(`<br/><button class="button button-primary button-small" id="orderSendGoodsBtn">Send Goods</button>`);
                $("#orderSendGoodsBtn").click(function () {
                    let tempJSON = { orderno: orderNo };
                    $.post(orderSendGoodsUrl, tempJSON, function (result) {
                        if (result.success) {
                            alert("success");
                            this.getOrder();
                        }
                        else {
                            alert(result.msg);
                        }
                    }.bind(this));
                }.bind(this));
            }
        }

        getStatusText(statusNumber) {
            let statusText = "Error";
            switch (statusNumber) {
                case 0: statusText = "已取消"; break;
                case 10: statusText = "未支付"; break;
                case 20: statusText = "已付款"; break;
                case 40: statusText = "已发货"; break;
                case 50: statusText = "订单完成"; break;
                case 60: statusText = "订单关闭"; break;
            }
            return statusText;
        }

        previousPage() {
            if (this.pageNum <= 1) {
                return;
            }
            this.pageNum--;
            this.getOrder();
        }

        nextPage() {
            if (this.pageNum >= this.pageTotal) {
                return;
            }
            this.pageNum++;
            this.getOrder();
        }
    }
    let productState = { getProduct: 0, showAddProduct: 1 };
    function productController(stateNumber) {
        switch (stateNumber) {
            case productState.getProduct:
                product.getProduct();
                break;
            case productState.showAddProduct:
                product.showAddProduct();
                break;
        }
    }
    let product;
    class Product {
        constructor() {
            this.productListBoxContent = $("#productListBox-content");
            this.productAddBoxContent = $("#productAddBox-content");
            this.pageJSONArray = [];
            this.searchText = null;
            this.searchState = {
                getById: 0,
                getByName: 1
            };
            this.pageNum = 1;
            this.pageSize = 10;
            this.pageTotal = 0;
            this.searchType = this.searchState.getByName;
            this.productListJSON = [];
        }

        showProduct() {
            let content = this.productListBoxContent;
            content.html("<h3><span class='title-Third'>Product List</span></h3>");
            content.append(`<select id="productSearchSelect">
                <option value="0" ${this.searchType === this.searchState.getById ? "selected" : ""}>By Id</option>
                <option value="1" ${this.searchType === this.searchState.getByName ? "selected" : ""}>By Name</option>
                </select>
                <input style="vertical-align: middle;" class="search-Input" id="productSearchInput" value="${this.searchText == null ? "" : this.searchText}"
                placeholder="input search text here."/>
                <button style="vertical-align: middle;" class="button button-primary button-small" id="productSearchBtn">Search</button><br/><br/>
                <div id="productSearchBox"></div>
            `);
            $("#productSearchSelect").on("change", function () {
                this.searchType = Number($("#productSearchSelect").val());
            }.bind(this));
            $("#productSearchInput").on("change", function () {
                let val = $("#productSearchInput").val();
                this.searchText = val;
            }.bind(this));
            $("#productSearchBtn").click(function () {
                this.pageNum = 1;
                this.getProduct();
            }.bind(this));
            for (let item of this.productListJSON) {
                content.append(`<div class="list-item" id="productDetail${item.id}"><div class="list-item-title">name</div>
                    <div class="list-item-content">${item.name}</div></div>`);
                $(`#productDetail${item.id}`).click(function () {
                    this.showDetail(item);
                }.bind(this));
            }
            content.append(`<br/><button class="button button-primary button-small" id="productPreviousPageBtn">Previous Page</button>
                <button class="button button-primary button-small" id="productNextPageBtn">Next Page</button>
            `);
            $(`#productPreviousPageBtn`).click(function () {
                this.previousPage();
            }.bind(this));
            $(`#productNextPageBtn`).click(function () {
                this.nextPage();
            }.bind(this));
        }

        showDetail(productJSON) {
            let content = this.productListBoxContent;
            content.html("");
            content.append(`<h3><span class="title-Third">Product Detail</span><button style="vertical-align: middle;"
                class="button button-primary button-small" id="backToProductList">Back</button></h3>
            `);
            $("#backToProductList").click(function () {
                this.showProduct();
            }.bind(this));
            content.append(`
                <div class="list-item"><div class="list-item-title">Name</div><div class="list-item-content">${productJSON.name}</div></div>
                <div class="list-item"><div class="list-item-title">Subtitle</div><div class="list-item-content">${productJSON.subtitle}</div></div>
                <div class="list-item"><div class="list-item-title">Price</div><div class="list-item-content">${productJSON.price}</div></div>
                <div class="list-item"><div  class="list-item-title">Status</div><div class="list-item-content">Put On Shelves<input type="radio" name="productDetailStatus" value="1" ${productJSON.status === 1 ? "checked" : ""}/>
                Pull Off Shelves<input type="radio" name="productDetailStatus" value="0" ${productJSON.status === 0 ? "checked" : ""}/></div></div><br/>
                <button class="button button-primary button-small" id="productSetSaleBtn">Update Shelves</button>
            `);
            $("#productSetSaleBtn").click(function () {
                let status = Number($("input[name='productDetailStatus']:checked").val());
                let tempJSON = { productId: productJSON.id, status: status };
                $.get(productSetSaleStatusUrl, tempJSON, function (result) {
                    if (result.success) {
                        alert("success");
                    }
                    else {
                        alert(result.msg);
                    }
                });
            }.bind(this));
        }

        getProduct() {
            let searchJSON = { pageNum: this.pageNum, pageSize: this.pageSize };
            if (this.searchType === this.searchState.getById) {
                searchJSON.productId = this.searchText;
            }
            else {
                searchJSON.productName = this.searchText;
            }
            $.get(productSearchListUrl, searchJSON, function (result) {
                if (result.success) {
                    if (result.data != null) {
                        this.productListJSON = result.data.list;
                        this.pageTotal = Math.ceil(result.data.total / this.pageSize);
                    }
                    else {
                        this.productListJSON = [];
                        this.pageTotal = 0;
                    }
                }
                else {
                    this.productListJSON = [];
                    this.pageTotal = 0;
                }
                this.showProduct();
            }.bind(this));
        }

        showAddProduct() {
            let content = this.productAddBoxContent;
            content.html("");
            content.append(`
                <div class="list-item"><div class="list-item-title">Name</div><input class="list-item-input" id="addProductNameInput" type="text" placeholder="input product name here."/></div>
                <div class="list-item"><div class="list-item-title">Subtile</div><input class="list-item-input" id="addProductSubtitleInput" type="text" placeholder="input product subtitle here."/></div>
                <div class="list-item"><div class="list-item-title">Detail</div><input class="list-item-input" id="addProductDetailInput" type="text" placeholder="input product detail here."/></div>
                <div class="list-item"><div class="list-item-title">Price</div><input class="list-item-input" id="addProductPriceInput" type="text" placeholder="input product price here."/></div>
                <div class="list-item"><div class="list-item-title">Stock</div><input class="list-item-input" id="addProductStockInput" type="text" placeholder="input product stock here."/></div>
                <div class="list-item"><div class="list-item-title">status</div><div class="list-item-content">Put On Shelves<input type="radio" value="1" name="productStatus" checked/>
                Pull Off Shelves<input type="radio" value="0" name="productStatus"/></div></div>
                <div class="list-item"><div class="list-item-title">Category</div><div class="list-item-content" id="categorySelectDiv"></div></div><br/>
                <button class="button button-primary button-small" id="addProductBtn">Add</button>
            `);
            let categorySelect = new CategorySelect(`#categorySelectDiv`);
            $("#addProductBtn").click(function () {
                let name = $("#addProductNameInput").val();
                let subtitle = $("#addProductSubtitleInput").val();
                let detail = $("#addProductDetailInput").val();
                let price = $("#addProductPriceInput").val();
                let stock = $("#addProductStockInput").val();
                let status = Number($("input[name='productStatus']:checked").val());
                let categoryId = categorySelect.getCurrentId();
                if (categoryId == null) {
                    alert("make sure you input category right.");
                    return;
                }
                let tempJSON = {
                    name: name,
                    subtitle: subtitle,
                    detail: detail,
                    price: price,
                    stock: stock,
                    status: status,
                    categoryId: categoryId
                };
                console.log(tempJSON);
                $.post(productSaveUrl, tempJSON, function (result) {
                    if (result.success) {
                        alert("success.");
                    }
                    else {
                        alert(result.msg);
                    }
                });
            });
        }

        previousPage() {
            if (this.pageNum <= 1) {
                return;
            }
            this.pageNum--;
            this.getProduct();
        }

        nextPage() {
            if(this.pageNum >= this.pageTotal) {
                return;
            }
            this.pageNum++;
            this.getProduct();
        }
    }
    class CategorySelect {
        constructor(contentDiv) {
            this.contentDiv = $(contentDiv);
            this.historyList = [];
            this.getChildrenJSON(0);
        }

        getChildrenJSON(categoryId) {
            let getJSON = {parentId: categoryId};
            $.get(categoryGetChildUrl, getJSON, function (result) {
                let children;
                if (result.success) {
                    children = result.data;
                }
                else {
                    children = [];
                }
                this.historyList.push({id: categoryId, children: children});
                this.showSelect();
            }.bind(this));
        }

        getCurrentId() {
            let temp = this.historyList[this.historyList.length - 1].id;
            if (temp === -1 || temp === 0) {
                temp = null;
            }
            return temp;
        }

        showSelect() {
            console.log(this.historyList);
            let content = this.contentDiv;
            content.html("");
            for (let i in this.historyList) {
                let elemStr = ``;
                if (this.historyList[i].children.length === 0) {
                    elemStr += `<span>No Children</span>`;
                }
                else {
                    elemStr += `<select id="categorySelect${i}">`;
                    elemStr += `<option value="-1" selected>---</option>`;
                    for (let item of this.historyList[i].children) {
                        elemStr += `<option value="${item.id}" ${this.historyList[i].selectId === item.id ? "selected" : ""}>${item.name}</option>`;
                    }
                    elemStr +=`</select>`;
                }
                content.append(elemStr);
                $(`#categorySelect${i}`).on("change", function () {
                    let val = $(`#categorySelect${i}`).val();
                    if (val != null) {
                        let index = Number(i);
                        val = Number(val);
                        this.historyList.splice(index + 1, this.historyList.length - index - 1);
                        this.historyList[index].selectId = val;
                        this.getChildrenJSON(val);
                    }
                }.bind(this));
            }
        }
    }
    let typeState = { getCategory: 0 };
    function typeController(stateNumber) {
        switch (stateNumber) {
            case typeState.getCategory:
                type.getCategory();
                break;
        }
    }
    let type;
    class Type {
        constructor() {
            this.currentId = 0;
            this.utils = new Utils();
            this.typeListBoxContent = $("#typeListBox-content");
            this.typeCategoryTree = { id: 0, children: [] };
            this.historyList = [];
        }

        getCategory() {
            let getJSON = {parentId: this.currentId};
            $.get(categoryGetChildUrl, getJSON, function (result) {
                let categoryJSON = this.getCategoryById(this.currentId, this.typeCategoryTree);
                if (result.success) {
                    for (let item of result.data) {
                        item.children = [];
                    }
                    categoryJSON.children = result.data;
                }
                else {
                    categoryJSON.children = [];
                }
                console.log(categoryJSON);
                this.showCategory(categoryJSON);
            }.bind(this));
        }

        pushHistory(categoryJSON) {
            this.historyList.push({ id: categoryJSON.id, name: categoryJSON.name });
        }

        showCategory(categoryJSON) {
            let content = this.typeListBoxContent;
            content.html("");
            if (this.historyList.length !== 0) {
                content.append(`<h3><span class="title-Third">Type List</span><button style="vertical-align: middle;"
                    class="button button-primary button-small" id="backToLastId">Back</button></h3>
                `);
                $("#backToLastId").click(function () {
                    let temp = this.historyList.pop();
                    this.currentId = temp.id;
                    this.getCategory();
                }.bind(this));
            }
            else {
                content.append(`<h3><span class="title-Third">Type List</span></h3><br/>`);
            }
            if (categoryJSON.id !== 0) {
                content.append(`<h4><span class="title-Type">${categoryJSON.name}</span>
                    <button style="vertical-align: middle;" class="button button-primary button-small" id="updateCategoryNameBtn">Update Category Name</button></h4>
                    <div id="updateCategoryNameDiv" style="display: none;">
                    <input style="vertical-align: middle;" class="search-Input" id="updateCategoryNameVal" placeholder="input category name here."/>
                    <button style="vertical-align: middle;" class="button button-primary button-small" id="doUpdateCategory">Update</button>
                    </div><br/><br/>
                `);
                $("#updateCategoryNameBtn").click(function () {
                    if ($("#updateCategoryNameDiv").css("display") === "none") {
                        $("#updateCategoryNameDiv").show();
                        $("#updateCategoryNameBtn").html("Cancel");
                    }
                    else {
                        $("#updateCategoryNameDiv").hide();
                        $("#updateCategoryNameBtn").html("Add Category");
                    }
                }.bind(this));
                $("#doUpdateCategory").click(function () {
                    let val = $("#updateCategoryNameVal").val();
                    console.log(val);
                    if (val != null) {
                        let getJSON = { categoryId: categoryJSON.id, categoryName: val };
                        $.get(categorySetNameUrl, getJSON, function (result) {
                            if (result.success) {
                                alert("success.");
                                categoryJSON.name = val;
                                this.getCategory();
                            }
                            else {
                                alert(result.msg);
                            }
                        }.bind(this));
                    }
                }.bind(this));
            }
            for (let item of categoryJSON.children) {
                content.append(`<div class="type-Item" id="category${item.id}"><h4>${item.name}</h4></div>`);
                $(`#category${item.id}`).click(function () {
                    console.log(item.id);
                    this.currentId = item.id;
                    this.pushHistory(categoryJSON);
                    this.getCategory();
                }.bind(this));
            }
            content.append(`<br/><button class="button button-primary button-small" id="addCategory">Add Category</button><br/>
                <div id="addCategoryDiv" style="display: none;">
                <input style="vertical-align: middle;" class="search-Input" id="newCategoryName" placeholder="input category name here."/>
                <button style="vertical-align: middle;" class="button button-primary button-small" id="doAddCategory">Add</button>
                </div>
               `);
            $("#addCategory").click(function () {
                if ($("#addCategoryDiv").css("display") === "none") {
                    $("#addCategoryDiv").show();
                    $("#addCategory").html("Cancel");
                }
                else {
                    $("#addCategoryDiv").hide();
                    $("#addCategory").html("Add Category");
                }
            }.bind(this));
            $("#doAddCategory").click(function () {
                let val = $("#newCategoryName").val();
                console.log(val);
                if (val != null) {
                    let getJSON = { parentId: categoryJSON.id, categoryName: val };
                    $.get(categoryAddUrl, getJSON, function (result) {
                        if (result.success) {
                            alert("success.");
                            this.getCategory();
                        }
                        else {
                            alert(result.msg);
                        }
                    }.bind(this));
                }
            }.bind(this));
        }

        getCategoryById(categoryId, categoryJSON) {
            if (categoryId === categoryJSON.id)
                return categoryJSON;
            if (categoryJSON.children.length === 0)
                return null;
            for (let item of categoryJSON.children) {
                if (this.getCategoryById(categoryId, item) != null) {
                    return this.getCategoryById(categoryId, item);
                }
            }
            return null;
        }
    }

    let userState = { getList: 0 };
    function userController(stateNumber) {
        switch (stateNumber) {
            case userState.getList:
                user.getList();
                break;
        }
    }
    let user;
    class User {
        constructor() {
            this.pageJSONArray = [];
            this.utils = new Utils();
            this.userListBoxContent = $("#userListBox-content");
            this.listPageNum = 1;
            this.listPageSize = 10;
            this.pageTotal = 0;
        }

        getList() {
            let temp = this.utils.getItem(this.pageJSONArray, `pageNum`, this.listPageNum);
            console.log(temp);
            if (temp != null) {
                this.showList();
                return;
            }
            let getJSON = { pageNum: this.listPageNum, pageSize: this.listPageSize };
            $.get(userGetListUrl, getJSON, function (result) {
                if (result.success) {
                    let data = result.data;
                    let userList = result.data.list;
                    this.pageTotal = Math.ceil(result.data.total / this.listPageSize);
                    this.pageJSONArray.push({pageNum: this.listPageNum, userList: userList});
                    //this.listPages = data.pages;
                    this.showList();
                }
            }.bind(this));
        }

        showList() {
            let pageNum = this.listPageNum;
            let content = this.userListBoxContent;
            let userList = this.utils.getItem(this.pageJSONArray, `pageNum`, pageNum);
            if (userList == null)
                return;
            userList = userList.userList;
            content.html("<h3><span class='title-Third'>User List</span></h3>");
            for (let item of userList) {
                content.append(`<div class="list-item" id="showDetail${item.id}"><div class="list-item-title">name</div>
                    <div class="list-item-content">${item.username}</div></div>`);
                $(`#showDetail${item.id}`).click(function () {
                    this.showDetail(pageNum, item.id);
                }.bind(this));
            }
            content.append(`
                <br/><button class="button button-primary button-small" id="listPreviousPageBtn">Previous Page</button>
                <button class="button button-primary button-small" id="listNextPageBtn">Next Page</button>
            `);
            $("#listPreviousPageBtn").click(function () {
                if (this.listPageNum <= 1)
                    return;
                this.listPageNum--;
                this.getList();
            }.bind(this));
            $("#listNextPageBtn").click(function () {
                if (this.listPageNum >= this.pageTotal)
                    return;
                this.listPageNum++;
                this.getList();
            }.bind(this));
        }

        showDetail(pageNum, userId) {
            let content = this.userListBoxContent;
            let userJSON = this.utils.getItem(this.utils.getItem(this.pageJSONArray, `pageNum`, pageNum).userList, `id`, userId);
            content.html("");
            content.append(`<h3><span class='title-Third'>User Detail</span><button style="vertical-align: middle;"
                class="button button-primary button-small" id="backToUserList">Back</button></h3>
                <div class="list-item"><div class="list-item-title">name</div><div class="list-item-content">${userJSON.username}</div></div>
                <div class="list-item"><div class="list-item-title">phone</div><div class="list-item-content">${userJSON.phone}</div></div>
                <div class="list-item"><div class="list-item-title">e-mail</div><div class="list-item-content">${userJSON.email}</div></div>
                <div class="list-item"><div class="list-item-title">time</div><div class="list-item-content">${userJSON.updatetime}</div></div>
                <div class="list-item"><div class="list-item-title">role</div><div class="list-item-content">${userJSON.role === 1 ? "Manager" : "User"}</div></div>
                <br/><button class="button button-primary button-small" id="jumpUpdateRole">Update User</button>
            `);

            this.listPageNum = pageNum;
            $("#backToUserList").click(function () {
                this.showList(this.listPageNum);
            }.bind(this));
            $("#jumpUpdateRole").click(function () {
                this.jumpUpdateRole(pageNum, userId, userJSON);
            }.bind(this));
        }

        jumpUpdateRole(pageNum, userId, userJSON) {
            let content = this.userListBoxContent;
            content.html("");
            content.append(`<h3><span class='title-Third'>User Update</span><button style="vertical-align: middle;"
                class="button button-primary button-small" id="backToDetail">Back</button></h3>
                <div class="list-item"><div class="list-item-title">name</div><div class="list-item-content">${userJSON.username}</div></div>
                <div class="list-item"><div class="list-item-title">role</div><div class="list-item-content"><input type="radio" value="1" name="userRole" ${userJSON.role === 1 ? "checked" : ""}/>Manager
                <input type="radio" value="0" name="userRole" ${userJSON.role === 0 ? "checked" : ""}/>User</div></div>
                <br/><button class="button button-primary button-small" id="updateRole">Update</button>
            `);
            $("#backToDetail").click(function () {
                this.showDetail(pageNum, userId);
            }.bind(this));
            $("#updateRole").click(function () {
                let val = Number($("input[name='userRole']:checked").val());
                this.updateRole(userId, val, userJSON);
            }.bind(this));
        }

        updateRole(userId, val, userJSON) {
            let postJSON = { userid: userId, role: val };
            $.post(userSetRoleUrl, postJSON, function (result) {
                if (result.success) {
                    userJSON.role = val;
                    alert(`success.`);
                }
            });
        }
    }
    class Utils {
        constructor() {

        }

        getItem(array, key, value) {
            let flag = null;
            for (let item of array) {
                if (item[key] === value) {
                    flag = item;
                    break;
                }
            }
            return flag;
        }
    }
</script>
</body>
</html>